import turbogears as tg
from turbogears import controllers, expose, flash, validators, redirect
from turbogears.widgets import WidgetsList, TableForm, TextField, HiddenField
from bookloantracker.model import *
import logging
log = logging.getLogger("bookloantracker.author")

from cherrypy import session

class AuthorFormList(WidgetsList):
    name = TextField(label=_("Name"),
                     validator=validators.NotEmpty(),
                     attrs={"size":"70"})
    info = TextField(label=_("Information"),
                     attrs={"size":"70"})
    webPage = TextField(label=_("Home Page"),
                        attrs={"size":"70"})
    retInfo = HiddenField()


authorForm = TableForm(
    fields = AuthorFormList(),
    action = "save",
    submit_text = _("Submit")
    )


class AuthorCadaster(controllers.Controller):
    @expose()
    def default(self, *k, **kw):
        redirect(tg.url("/"))

    @expose(template="bookloantracker.templates.authorcadaster")
    def index(self, name=None, ret=None):
        values = {}
        if name:
            values["name"] = name
        if ret:
            values["retInfo"] = ret
        return dict(form = authorForm,
                    values = values)

    @expose()
    def save(self, name, info=None, 
             webPage=None, retInfo=None):
        redirectTarget = "index"
        if retInfo:
            redirectTarget = "/"+"/".join(retInfo.split("."))
        log.debug("redirectTarget = %s" % redirectTarget)
        authorList = Author.selectBy(name=name)
        if authorList.count():
            flash(_("Author alredy registered"))
            redirect(redirectTarget)
        author = Author(name = name,
                        webPage = webPage,
                        info = info)
        flash(_("Author registered"))
        redirect(redirectTarget)
        return {}
